//
//  BPSubmitCommentViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/2/21.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPSubmitCommentViewController.h"

@interface BPSubmitCommentViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *star1;
@property (weak, nonatomic) IBOutlet UIButton *star2;
@property (weak, nonatomic) IBOutlet UIButton *star3;
@property (weak, nonatomic) IBOutlet UIButton *star4;
@property (weak, nonatomic) IBOutlet UIButton *star5;

@property (weak, nonatomic) IBOutlet UIView *tagView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagViewHeight;

@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (strong, nonatomic) NSArray *tagNames;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *whiteViewHeight;

@property (strong, nonatomic) NSArray *tagsData;

@property (weak, nonatomic) IBOutlet UIButton *picBtn1;
@property (weak, nonatomic) IBOutlet UIButton *picBtn2;
@property (weak, nonatomic) IBOutlet UIButton *picBtn3;
@property (weak, nonatomic) IBOutlet UIButton *picBtn4;

@property (weak, nonatomic) IBOutlet UIButton *commitComment;

@property (strong, nonatomic) UIButton *selectedPicBtn;

@property (assign, nonatomic) NSUInteger picCount;

//选中的星级
@property (strong, nonatomic) NSString *selectedStarLevel;
//选中的标签
@property (strong, nonatomic) NSMutableArray *selectedTagsIndex;
//记录下上传图片的id
@property (strong, nonatomic) NSMutableArray *picIDs;

@end

@implementation BPSubmitCommentViewController

- (NSMutableArray *)selectedTagsIndex {
    if (_selectedTagsIndex == nil) {
        _selectedTagsIndex = [NSMutableArray array];
    }
    return _selectedTagsIndex;
}

- (NSMutableArray *)picIDs {
    if (_picIDs == nil) {
        _picIDs = [NSMutableArray array];
    }
    return _picIDs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发表评论";
    //默认评价为5星
    self.selectedStarLevel = @"5";
    //初始设置无图片
    self.picCount = 0;
    _commitComment.layer.cornerRadius = 8.0;
    
    _picBtn2.hidden = YES;
    _picBtn3.hidden = YES;
    _picBtn4.hidden = YES;
    
    _star1.selected = YES;
    _star2.selected = YES;
    _star3.selected = YES;
    _star4.selected = YES;
    _star5.selected = YES;
    
    _star1.adjustsImageWhenHighlighted = NO;
    _star2.adjustsImageWhenHighlighted = NO;
    _star3.adjustsImageWhenHighlighted = NO;
    _star4.adjustsImageWhenHighlighted = NO;
    _star5.adjustsImageWhenHighlighted = NO;
    
    _whiteViewHeight.constant = _picBtn4.bottom + 10;
    [self.view layoutIfNeeded];
    [self getData];
    
}

- (void)getData {
    [SVProgressHUD showWithStatus:@"读取中..."];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    [mgr POST:[NSString stringWithFormat:@"%@?c=Order&&a=evaluateByStar",requestURL]
   parameters:@{}
     progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
             [SVProgressHUD dismiss];
             self.tagsData = responseObject[@"data"];
             NSLog(@"%@", self.tagsData);
             //获取5星对应的标签
             NSArray *fiveStarSigns = [self.tagsData lastObject][@"signs"];
             NSMutableArray *temp = [NSMutableArray array];
             for (NSDictionary *dict in fiveStarSigns) {
                 [temp addObject:dict[@"sign"]];
             }
             _tagNames = temp;
             
             //设置标签
             [self setupTags];
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];
}

- (void)touchTagBtn:(UIButton *)button {
    button.selected = !button.isSelected;
    if (button.isSelected) {
        NSArray *starSigns = self.tagsData[[self.selectedStarLevel integerValue] - 1][@"signs"];
        [self.selectedTagsIndex addObject:starSigns[button.tag][@"id"]];
    }
}

- (void)setupTags {
    //记录上一个tag的frame
    CGRect lastTagFrame;
    for (NSInteger i = 0; i < _tagNames.count; i++) {
        UIButton *tag = [UIButton buttonWithType:UIButtonTypeCustom];
        tag.tag = i;
        tag.adjustsImageWhenHighlighted = NO;
        [tag addTarget:self action:@selector(touchTagBtn:) forControlEvents:UIControlEventTouchUpInside];
        NSString *title = [NSString stringWithFormat:@" %@ ", _tagNames[i]];
        [tag setTitle:title forState:UIControlStateNormal];
        [tag.titleLabel setFont:[UIFont fontWithName:@"PingFangSC-Regular" size:14]];
        [tag setTitleColor:[UIColor colorWithRed:185/255.0 green:198/255.0 blue:208/255.0 alpha:1/1.0] forState:UIControlStateNormal];
        [tag setTitleColor: [UIColor colorWithRed:118/255.0 green:177/255.0 blue:253/255.0 alpha:1/1.0] forState:UIControlStateSelected];
        [tag setBackgroundImage:[UIImage imageNamed:@"tag_no"] forState:UIControlStateNormal];
        [tag setBackgroundImage:[UIImage imageNamed:@"tag_selected"] forState:UIControlStateSelected];
        [tag sizeToFit];
        if (i == 0) {
            tag.origin = CGPointMake(0, 0);
        }
        else {
            tag.origin = CGPointMake(lastTagFrame.origin.x + lastTagFrame.size.width + 10, lastTagFrame.origin.y);
            //换行
            if (tag.right > _tagView.width) {
                tag.origin = CGPointMake(0, lastTagFrame.size.height + lastTagFrame.origin.y + 14);
            }
        }
        lastTagFrame = tag.frame;
        [_tagView addSubview:tag];
        //根据最后一个tag设置tagView的高度
        if (i == _tagNames.count - 1) {
            _tagViewHeight.constant = tag.bottom + 10;
            [self.view layoutIfNeeded];
        }
    }
    //更新white view的高度
    _whiteViewHeight.constant = _picBtn4.bottom + 10;
}

- (IBAction)clickStar:(UIButton *)button {
    //先移除所有的tag
    for (UIButton *btn in _tagView.subviews) {
        [btn removeFromSuperview];
    }
    NSArray *fiveStarSigns = self.tagsData[button.tag - 1][@"signs"];
    NSMutableArray *temp = [NSMutableArray array];
    for (NSDictionary *dict in fiveStarSigns) {
        [temp addObject:dict[@"sign"]];
    }
    _tagNames = temp;
    //记录选择的星级
    self.selectedStarLevel = [NSString stringWithFormat:@"%lu", button.tag];
    //移除所有之前选择的tag
    [self.selectedTagsIndex removeAllObjects];
    
    switch (button.tag) {
        case 1:
        {
            _star2.selected = NO;
            _star3.selected = NO;
            _star4.selected = NO;
            _star5.selected = NO;
        }
            break;
        case 2:
        {
            _star2.selected = YES;
            _star3.selected = NO;
            _star4.selected = NO;
            _star5.selected = NO;
        }
            break;
        case 3:
        {
            _star2.selected = YES;
            _star3.selected = YES;
            _star4.selected = NO;
            _star5.selected = NO;
        }
            break;
        case 4:
        {
            _star2.selected = YES;
            _star3.selected = YES;
            _star4.selected = YES;
            _star5.selected = NO;
        }
            break;
        case 5:
        {
            _star2.selected = YES;
            _star3.selected = YES;
            _star4.selected = YES;
            _star5.selected = YES;
        }
            break;
        default:
            break;
    }
    [self setupTags];
}

- (IBAction)addPicBtn:(UIButton *)button {
    self.selectedPicBtn = button;
    
    //图片选择控制器
    UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
    //设置进入本地的哪个相册
    imagePickerC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //设置代理实现图片的选中
    imagePickerC.delegate = self;
    
    [self presentViewController:imagePickerC animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获取选中的图片
    UIImage *selectedImage =  info[UIImagePickerControllerOriginalImage];
    [self.selectedPicBtn setImage:selectedImage forState:UIControlStateNormal];
    //退出图片选择器
    [self dismissViewControllerAnimated:NO completion:^{
        //添加图片成功，将是否有图片的BOOL值做更改
        self.picCount++;
        //右上角添加一个删除按钮
        UIButton *removePicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [removePicBtn setBackgroundImage:[UIImage imageNamed:@"delete_pic"] forState:UIControlStateNormal];
        [removePicBtn sizeToFit];
        removePicBtn.origin = CGPointMake(self.selectedPicBtn.width - removePicBtn.width, 0);
        [self.selectedPicBtn addSubview:removePicBtn];
        [removePicBtn addTarget:self action:@selector(removePic:) forControlEvents:UIControlEventTouchUpInside];
        
        //将下一个添加图片按钮设为可见，并将前一个删除图片的按钮设为隐藏
        switch (self.selectedPicBtn.tag) {
            case 11:
            {
                _picBtn2.hidden = NO;
            }
                break;
            case 22:
            {
                _picBtn3.hidden = NO;
            }
                break;
            case 33:
            {
                _picBtn4.hidden = NO;
            }
                break;
                
            default:
                break;
        }
    }];
}

- (void)removePic:(UIButton *)removeBtn {
    //获取当前按钮
    UIButton *button = (UIButton *)[removeBtn superview];
    [button setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
    [removeBtn removeFromSuperview];
    switch (button.tag) {
        case 11:
        {
            //将第一个图片删除了, 后面所有图片都默认删除，设置为无图片情况
            self.picCount = 0;
            _picBtn2.hidden = YES;
            [_picBtn2 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
            _picBtn3.hidden = YES;
            [_picBtn3 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
            _picBtn4.hidden = YES;
            [_picBtn4 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
        }
            break;
        case 22:
        {
            self.picCount = 1;
            _picBtn3.hidden = YES;
            [_picBtn3 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
            _picBtn4.hidden = YES;
            [_picBtn4 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
        }
            break;
        case 33:
        {
            self.picCount = 2;
            _picBtn4.hidden = YES;
            [_picBtn4 setImage:[UIImage imageNamed:@"addPhoto"] forState:UIControlStateNormal];
        }
            break;
        case 44:
        {
            self.picCount = 3;
        }
            break;
        default:
            break;
    }
}
- (IBAction)commitCommentBtn:(UIButton *)sender {
    
    NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    //判断是否有图片
    if (self.picCount) {
        [SVProgressHUD showWithStatus:@"上传图片中..."];
        //有几张传几次
        for (NSInteger i = 0; i < self.picCount; i++) {
            UIImage *img = [[UIImage alloc]init];
            //取得本次要上传的图片
            switch (i) {
                case 0:
                {
                    img = _picBtn1.imageView.image;
                }
                    break;
                case 1:
                {
                    img = _picBtn2.imageView.image;
                }
                    break;
                case 2:
                {
                    img = _picBtn3.imageView.image;
                }
                    break;
                case 3:
                {
                    img = _picBtn4.imageView.image;
                }
                    break;
                default:
                    break;
            }
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            //接收类型不一致请替换一致text/html或别的
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                 @"text/html",
                                                                 @"image/jpeg",
                                                                 @"image/png",
                                                                 @"application/octet-stream",
                                                                 @"text/json",
                                                                 @"text/plain",
                                                                 nil];
            NSDictionary * dict = @{
                                    @"token" : user[@"token"],
                                    @"type" : @"1"
                                    };
            [manager POST:[NSString stringWithFormat:@"%@?c=User&&a=uploadAttach",requestURL]
               parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                   
                   NSData *imageData = UIImageJPEGRepresentation(img, 1);
                   
                   if (imageData.length > 5000000) {
                       imageData = UIImageJPEGRepresentation(img, 0.1);
                   }
                   else if (imageData.length > 3000000) {
                       imageData = UIImageJPEGRepresentation(img, 0.3);
                   }
                   else if (imageData.length > 1000000) {
                       imageData = UIImageJPEGRepresentation(img, 0.5);
                   }
                   
                   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                   formatter.dateFormat = @"yyyyMMddHHmmss";
                   NSString *str = [formatter stringFromDate:[NSDate date]];
                   NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                   
                   //上传的参数(上传图片，以文件流的格式)
                   [formData appendPartWithFileData:imageData
                                               name:@"img"
                                           fileName:fileName
                                           mimeType:@"image/jpeg"];
                   
               } progress:^(NSProgress * _Nonnull uploadProgress) {
                   //打印下上传进度
                   NSLog(@"第%li张图片: %@", (long)(i + 1), uploadProgress);
               } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                   if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                       NSLog(@"第%li张图片上传完成", (long)(i + 1));
                       [self.picIDs addObject:responseObject[@"data"][@"id"]];
                       
                       //所有图片上传完成后，拿到所有的图片ID，上传评论
                       if (self.picIDs.count == self.picCount) {
                           
                           NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                           dict[@"token"] = user[@"token"];
                           dict[@"starLevel"] = self.selectedStarLevel;
                           dict[@"orderID"] = self.orderID;
                           dict[@"sign"] = self.selectedTagsIndex;
                           dict[@"attach"] = self.picIDs;
                           if([self.textView.text length] > 0) {
                               dict[@"more"] = self.textView.text;
                           }
                           [SVProgressHUD showWithStatus:@"上传评价中..."];
                           AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
                           mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                            @"text/html",
                                                                            @"image/jpeg",
                                                                            @"image/png",
                                                                            @"application/octet-stream",
                                                                            @"text/json",
                                                                            nil];
                           [mgr POST:[NSString stringWithFormat:@"%@?c=Order&&a=evaluateOrder",requestURL]
                          parameters:dict
                            progress:^(NSProgress * _Nonnull uploadProgress) {
                                
                            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                                    [SVProgressHUD dismiss];
                                    NSLog(@"%@", responseObject);
                                    //评价成功 pop
                                    [SVProgressHUD showInfoWithStatus:@"评价成功"];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [self.navigationController popToRootViewControllerAnimated:YES];
                                        [SVProgressHUD dismiss];
                                    });
                                }
                                else {
                                    [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"%@", responseObject[@"data"]]];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [SVProgressHUD dismiss];
                                    });
                                }
                            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                
                            }];
                       }
                   }
                   else {
                       [SVProgressHUD showInfoWithStatus:@"上传失败"];
                       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                           [SVProgressHUD dismiss];
                       });
                   }
                   
               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                   [SVProgressHUD showInfoWithStatus:@"请求失败"];
                   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                       [SVProgressHUD dismiss];
                   });
               }];
        }
        
        
    }
    //无图片直接上传评论
    else {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"token"] = user[@"token"];
        dict[@"starLevel"] = self.selectedStarLevel;
        dict[@"orderID"] = self.orderID;
        dict[@"sign"] = self.selectedTagsIndex;
        
        if([self.textView.text length] > 0) {
            dict[@"more"] = self.textView.text;
        }
        [SVProgressHUD showWithStatus:@"上传评价中..."];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        [mgr POST:[NSString stringWithFormat:@"%@?c=Order&&a=evaluateOrder",requestURL]
       parameters:dict
         progress:^(NSProgress * _Nonnull uploadProgress) {
             
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                 [SVProgressHUD dismiss];
                 //评价成功 pop
                 [SVProgressHUD showInfoWithStatus:@"评价成功"];
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [SVProgressHUD dismiss];
                     [self.navigationController popToRootViewControllerAnimated:YES];
                 });
             }
             else {
                 [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"%@", responseObject[@"data"]]];
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [SVProgressHUD dismiss];
                 });
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
         }];
    }
}

@end
